package cn.rxmind.dlog.common.interceptor;

import cn.rxmind.dlog.common.AbstractDLogInterceptor;
import cn.rxmind.dlog.common.DLogDataBuffer;
import cn.rxmind.dlog.common.DLogProperties;
import org.apache.commons.lang3.StringUtils;
import org.springframework.context.ApplicationContext;
import org.springframework.util.AntPathMatcher;
import org.springframework.web.method.HandlerMethod;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.HashMap;
import java.util.Map;

/**
 *
 * @description 根据URL正则匹配决定数据接口是否该采集
 *
 * @author renxin
 * @email renxinzhiliangzhi@163.com
 * @date 2020/7/13 3:07 下午
 */
public class UriRuleDLogInterceptor extends AbstractDLogInterceptor {

    private final AntPathMatcher PATH_MATCHER = new AntPathMatcher ();

    public UriRuleDLogInterceptor(DLogProperties dLogProperties, DLogDataBuffer dLogDataBuffer, ApplicationContext applicationContext) {
        super(dLogProperties, dLogDataBuffer, applicationContext);
    }

    @Override
    protected Map<String, Object> createExtendParam(HttpServletRequest request, HttpServletResponse response, Object handler) {
        return new HashMap<>();
    }

    @Override
    protected boolean needCollect(HttpServletRequest request, HandlerMethod handlerMethod, DLogProperties dLogProperties) {

        if(StringUtils.isNotBlank(dLogProperties.getIgnoreUriPattern()) && PATH_MATCHER.match(dLogProperties.getIgnoreUriPattern(),request.getRequestURI())){
            return false;
        }

        if(StringUtils.isNotBlank(dLogProperties.getCollectUriPattern())){

            return PATH_MATCHER.match(dLogProperties.getCollectUriPattern(),request.getRequestURI());
        }

        return true;
    }
}
